<template>
  <div class="flex items-center">
    <a-spin :loading="loading" tip="加载中...">
      <a-form
        ref="formRef"
        :model="formData"
        class="form"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item
          field="title"
          label="题目标题"
          :rules="[
            {
              required: true,
              message: '请填写标题'
            }
          ]"
        >
          <a-input v-model="formData.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item
          field="tags"
          label="题目标签"
          :rules="[
            {
              required: true,
              message: '请输入标签'
            }
          ]"
        >
          <a-input-tag
            v-model="formData.tags"
            placeholder="输入标签并点击回车"
          />
        </a-form-item>
        <a-form-item
          field="difficulty"
          label="题目难度"
          :rules="[
            {
              required: true,
              message: '请选择题目难度'
            }
          ]"
        >
          <a-select
            v-model="formData.difficulty"
            :options="difficultyOptions"
            placeholder="请选择题目难度"
            @change="(val) => console.log('难度选择改变:', val)"
          >
            <template #option="{ value, label }">
              <span :style="{ color: value === 0 ? '#52C41A' : value === 1 ? '#FA8C16' : '#F5222D' }">
                {{ label }}
              </span>
            </template>
          </a-select>
        </a-form-item>
        <div style="text-align: center">
          <a-button type="primary" @click="onNextClick">下一步</a-button>
        </div>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, unref, watch } from 'vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { OjProblemAddRequest, OjProblemVo } from '@/api/gen-api';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';

const emits = defineEmits(['changeStep', 'update:data']);
const formRef = ref<FormInstance>();
const formData = ref<OjProblemAddRequest>({
  title: '',
  tags: [],
  difficulty: 0
});
const difficultyOptions = [
  { label: '入门', value: 0 },
  { label: '进阶', value: 1 },
  { label: '挑战', value: 2 }
];

const getDifficultyLabel = (value) => {
  const numValue = typeof value === 'string' ? parseInt(value, 10) : value;
  
  console.log('难度选择值类型:', typeof value, '原始值:', value, '转换值:', numValue);
  
  switch(numValue) {
    case 0:
      return '入门';
    case 1:
      return '进阶';
    case 2:
      return '挑战';
    default:
      if (value === '简单') return '入门';
      if (value === '中等') return '进阶';
      if (value === '困难') return '挑战';
      console.warn('未识别的难度值:', value);
      return '未知难度';
  }
};

const onNextClick = async () => {
  try {
    // 调用表单验证
    await formRef.value?.validate();
    // 表单验证通过时继续执行下一步
    emits('changeStep', 'forward');
  } catch (error) {
    // 验证失败时不进行操作，停留在当前页面
    console.log('表单验证失败:', error);
  }
};

const props = defineProps({
  data: {
    type: Object as () => OjProblemVo | undefined,
    default: () => ({})
  },
  addFlag: {
    type: Boolean,
    default: true
  }
});

const loading = ref(true);
watch(
  () => props.data,
  (newData) => {
    console.log('接收到题目数据变更:', newData);
    if (!newData) return;
    
    // 避免在数据加载中重复设置
    if (loading.value) return;
    
    nextTick(() => {
      const { title, tags, difficulty } = newData;
      
      // 记录原始值
      console.log('更新表单数据 - 原始值:', { 
        difficulty: formData.value.difficulty, 
        title: formData.value.title, 
        tags: formData.value.tags 
      });
      
      // 确保数据类型正确
      formData.value.title = title || '';
      formData.value.tags = Array.isArray(tags) ? tags : [];
      formData.value.difficulty = typeof difficulty === 'number' ? difficulty : 
        (typeof difficulty === 'string' ? parseInt(difficulty, 10) : 0);
      
      // 更新后的值
      console.log('更新表单数据 - 更新后:', formData.value);
    });
  }
);

watch(
  () => formData.value,
  (newFormData) => {
    console.log('表单数据变化:', newFormData);
    // 向父组件同步数据
    emits('update:data', { ...newFormData });
  },
  { deep: true }
);

onMounted(() => {
  console.log('ProblemBaseInfo组件加载 - addFlag:', props.addFlag);
  
  // 如果是添加模式，无需等待数据加载
  if (props.addFlag) {
    console.log('添加模式，直接设置默认值');
    loading.value = false;
  }
  // 如果是编辑模式且有数据，则加载数据
  else if (props.data) {
    console.log('编辑模式，加载数据:', props.data);
    const { title, tags, difficulty } = props.data;
    
    // 设置表单数据
    formData.value.title = title || '';
    formData.value.tags = Array.isArray(tags) ? tags : [];
    formData.value.difficulty = typeof difficulty === 'number' ? difficulty : 0;
    
    console.log('设置后的表单数据:', formData.value);
    loading.value = false;
  }
});
</script>

<style scoped lang="less">
.form {
  width: 457px;
}

.form-content {
  padding: 8px 50px 0 30px;
}
</style>
